package com.app.couponsharelife.ui.main.home.shopweb

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.util.Log
import android.view.View
import androidx.lifecycle.ViewModelProviders
import com.alibaba.baichuan.android.trade.AlibcTrade
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback
import com.alibaba.baichuan.android.trade.model.AlibcShowParams
import com.alibaba.baichuan.android.trade.model.OpenType
import com.alibaba.baichuan.android.trade.page.AlibcPage
import com.alibaba.baichuan.trade.biz.AlibcConstants
import com.alibaba.baichuan.trade.biz.context.AlibcResultType
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams
import com.google.gson.Gson
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.TBBandRealtionBean
import com.app.couponsharelife.data.bean.TaobaoGoodBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.main.home.good.GoodShareActivity
import com.app.couponsharelife.ui.main.login.NewLoginActivity
import com.app.couponsharelife.ui.viewmodel.HomeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import com.tencent.smtt.sdk.*
import com.tencent.smtt.utils.TbsLog
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_shop_web.*
import okhttp3.MediaType
import okhttp3.RequestBody
import org.jsoup.Jsoup
import java.net.URISyntaxException
import java.util.*

class ShopWebActivity : BaseActivity() {
    override val viewLayoutId: Int get() = R.layout.activity_shop_web
    private var mViewModel: HomeViewModel? = null
    private var title = ""
    private var itemId = ""
    private var showDetail = true
    private var goodBean: TaobaoGoodBean? = null
    private var alibcShowParams: AlibcShowParams? = null//页面打开方式，默认，H5，Native
    private var exParams: HashMap<String, String>? = null//yhhpass参数
    private var alibcTaokeParams: AlibcTaokeParams? = null//淘客参数，包括pid，unionid，subPid
    private var url=""
    private var oldurl=""
    private var name=""
    private var webSettings:WebSettings?=null
    private var mAlertdialog:AlertDialog.Builder?=null
    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        initToolBar()
        initWebView()
    }

    private fun initToolBar() {
        //AppUtils.setWindowStatusBarColor(this, R.color.black)
        ivBack.setOnClickListener { onBackPressed() }
        ivFinish.setOnClickListener { finish() }
        name=intent!!.getStringExtra("name")?:""
        tvToolBarTitle.text = name
        tvFindCoupon.setOnClickListener { loadOptionalGoods() }
        tvShareGood.setOnClickListener {
            if (AppUtils.checkUserLogin())  // && judgeAdzoneIdExist()
                goShare()
            else
                //startActivity(Intent(this@ShopWebActivity, LoginActivity::class.java))
                startActivity(Intent(this@ShopWebActivity, NewLoginActivity::class.java))
        }
        tvGetCoupon.setOnClickListener {
            if (AppUtils.checkUserLogin())  // && judgeAdzoneIdExist()
                goTaoBao()
            else
                //startActivity(Intent(this@ShopWebActivity, LoginActivity::class.java))
                startActivity(Intent(this@ShopWebActivity, NewLoginActivity::class.java))
        }
    }

    private fun initWebView() {
        url=intent!!.getStringExtra("url")?:""
        showProgressDialog("请稍候")
        mWebView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                if (newProgress == 100) {
                    dismissProgressDialog()
                    mWebView.visibility = View.VISIBLE
                }
                super.onProgressChanged(view, newProgress)
            }
        }
        mWebView.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                if (url != null && url.contains("https://detail")) {
                    clBotContainer.visibility = View.VISIBLE
                    tvTopTipContainer.visibility = View.VISIBLE
                    tvFindCoupon.visibility = View.VISIBLE
                    tvFindCoupon.text = "一键找券查佣金"
                    clCouponResult.visibility = View.GONE
                    showDetail = true
                } else
                    showDetail = false
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                //Log.e("error", url)
                if (url != null && url.contains("https://detail")) {
                    if (itemId == "" && title == "") {
                        clBotContainer.visibility = View.VISIBLE
                        tvTopTipContainer.visibility = View.VISIBLE
                        tvFindCoupon.visibility = View.VISIBLE
                        clCouponResult.visibility = View.GONE
                        val string = AppUtils.getURLDecoderString(url)
                        val array = string.split("&")
                        for (str in array) {
                            if (str.contains("id=")) {
                                itemId = str.substring(str.indexOf("id=") + 3)
                                title = ""
                                break
                            } else if (str.contains("item_id=")) {
                                itemId = str.substring(str.indexOf("item_id=") + 8)
                                title = ""
                                break
                            }
                        }
                        if (itemId != "")
                            parseHtml("https://detail.tmall.com/item.htm?id=$itemId")
                    }
                } else {
                    if (!showDetail) {
                        clBotContainer.visibility = View.GONE
                        tvTopTipContainer.visibility = View.GONE
                    }
                }
                super.onPageFinished(view, url)
            }

            override fun shouldOverrideUrlLoading(p0: WebView?, url: String?): Boolean {
                if (url!=null&&url.isNotEmpty()){
                    if (url.startsWith("http") || url.startsWith("https") || url.startsWith("ftp")){
                        //Log.e("eee","常规链接---->${url}")
                        //http://127.0.0.1:12345/error?code=fdWuTuXdwFgZHQ8smRnueUlB4290749&state=1212
                        if (url.startsWith("http://127.0.0.1:12345")){
                            val arr=url.split("code=")
                            if (arr.size>1){
                                val arr1=arr[1].split("&")
                                if (arr1.size>1){
                                    val code=arr1[0]?:""
                                    if (code.isNotEmpty()){
                                        bindRlId(code)
                                    }
                                }
                            }
                            return true
                        }else{
                            return super.shouldOverrideUrlLoading(p0, url)
                        }
                    }else{
                        if (url.startsWith("tbopen://")){
                            return true
                        }else{
                            //Log.e("eee","AppUri---->${url}")
                            var intent:Intent?=null
                            try {
                                intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
                            } catch (e: URISyntaxException) {
                                return false
                            }
                            intent.setComponent(null)
                            try {
                                startActivity(intent)
                            } catch (e: ActivityNotFoundException) {
                                return false
                            }
                            return true
                        }
                    }
                }else{
                    return super.shouldOverrideUrlLoading(p0, url)
                }
            }
        }
        setWebString(url)
    }
    private fun setWebString(mIntentUrl:String){
        webSettings=mWebView.settings
        webSettings!!.allowFileAccess = true
        webSettings!!.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        webSettings!!.setSupportZoom(true)
        webSettings!!.builtInZoomControls = true
        webSettings!!.useWideViewPort = true
        webSettings!!.setSupportMultipleWindows(false)
        // webSetting.setLoadWithOverviewMode(true);
        webSettings!!.setAppCacheEnabled(true)
        // webSetting.setDatabaseEnabled(true);
        webSettings!!.domStorageEnabled = true
        webSettings!!.setJavaScriptEnabled(true)
        webSettings!!.setGeolocationEnabled(true)
        webSettings!!.setAppCacheMaxSize(java.lang.Long.MAX_VALUE)
        webSettings!!.setAppCachePath(this.getDir("appcache", 0).path)
        webSettings!!.databasePath = this.getDir("databases", 0).path
        webSettings!!.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .path)
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSettings!!.pluginState = WebSettings.PluginState.ON_DEMAND
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        val time = System.currentTimeMillis()
        mWebView.loadUrl(mIntentUrl)
        TbsLog.d("time-cost", "cost time: " + (System.currentTimeMillis() - time))
        CookieSyncManager.createInstance(this)
        CookieSyncManager.getInstance().sync()
    }
    @SuppressLint("CheckResult")
    private fun parseHtml(url: String) {
        //Log.e("error", url)
        if (title == "") {
            Observable.just(url)
                    .map {
                        val res = Jsoup.connect(url).header("Accept", "*/*")
                                .header("Accept-Encoding", "gzip, deflate")
                                .header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
                                .header("Content-Type", "application/json;charset=UTF-8")
                                .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
                                .timeout(10000).ignoreContentType(true).execute()
                        val titles = res.parse().getElementsByTag("title")
                        for (t in titles) {
                            Log.e("error", t.html())
                            val text = t.text()
                            title = if (text.contains("-"))
                                text.substring(0, text.indexOf("-"))
                            else text
                        }
                        title
                    }.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        itemId = ""
                        if (title != "") {
                            tvToolBarTitle.text = title
                        }
                    }, {
                        itemId = ""
                        Log.e("error", it.message)
                    })
        }
    }
    fun showMessageDialog(msg: String,url:String) {
        if (mAlertdialog!=null&&!mAlertdialog!!.create().isShowing){
            return
        }
        if (!isFinishing) {//activity未关闭 显示dialog
            if (mAlertdialog == null) {
                mAlertdialog = AlertDialog.Builder(this)
                mAlertdialog!!.setPositiveButton("确定") { dialog, which ->
                    val intent=Intent()
                    intent.data = Uri.parse(url)
                    startActivity(intent)
                    dismissMessageDialog()
                }
                mAlertdialog!!.setNegativeButton("取消") { dialog, which ->
                    mWebView.loadUrl(oldurl)
                    dismissMessageDialog()
                }
            }
            mAlertdialog!!.setTitle(msg)
            if (!mAlertdialog!!.create().isShowing) {
                mAlertdialog!!.create().show()
            }
        }
    }

    fun dismissMessageDialog() {
        if (mAlertdialog != null && !isFinishing) {
            mAlertdialog!!.create().dismiss()
        }
    }
    private fun loadOptionalGoods() {
        if (goodBean != null || title == "") return
        val map = HashMap<String, String>()
        map["pageNo"] = "1"
        map["adzoneid"] = if (AppUtils.getString(Contacts.ADZONE_ID, "") == "") Contacts.DEFAULT_ADZONE_ID else AppUtils.getString(Contacts.ADZONE_ID, "")
        map["words"] = title
        map["iscoupon"] = "0"
        map["timestamp"] = (System.currentTimeMillis() / 1000).toString()
        map["sign"] = AppUtils.getMapString(map)
        map["param"] = Gson().toJson(TreeMap(map).descendingMap())
        mViewModel!!.refreshShopOptionalSearch(map, true)
    }
    private fun bindRlId(code:String){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        map["userId"]=AppUtils.getString(Contacts.USERID,"")
        map["code"]=code
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        RetrofitWorker.retrofitWorker.bandRealtion(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), Gson().toJson(map)))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object :DisposableObserver<RemoteResultBean<TBBandRealtionBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<TBBandRealtionBean>) {
                        dismissProgressDialog()
                        if (200==it.code){
                            AppUtils.setString(Contacts.ADZONE_ID, it.data!!.relationId?:"")
                            showToastMsg("授权绑定成功！")
                            finish()
                        }else{
                            showToastMsg("授权绑定失败！")
                            finish()
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错！")
                        }
                        finish()
                    }
                })
    }
    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(HomeViewModel::class.java)
        if (!mViewModel!!.shopOptionalSearch()!!.hasObservers()) {
            mViewModel!!.shopOptionalSearch()!!.observe(this, androidx.lifecycle.Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("正在查询")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshShopOptionalSearch(hashMapOf(), false)
                        if (it.error!!.message == "调用出错，请重新尝试")
                            tvFindCoupon.text = "该商品未参与推广，请换个试试"
                        else
                            print(it.error.message)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshShopOptionalSearch(hashMapOf(), false)
                        println("暂无更多商品")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshShopOptionalSearch(hashMapOf(), false)
                        if (it.data!!.data!!.couponGood != null) {
                            tvFindCoupon.visibility = View.GONE
                            clCouponResult.visibility = View.VISIBLE
                            goodBean = it.data.data!!.couponGood!!
                            tvShareGood.text = "分享赚¥ ${it.data.data!!.couponGood!!.vip_commission}"
                            if (it.data.data!!.couponGood!!.has_coupon) {
                                tvGetCoupon.text = "领${it.data.data!!.couponGood!!.coupon_price}元券"
                            } else {
                                tvGetCoupon.text = "立即购买"
                            }
                        } else {
                            tvFindCoupon.text = "该商品未参与推广，请换个试试"
                        }
                    }
                }
            })
        }
    }
    private fun getPager():Boolean{
        var pack:PackageInfo?=null
        try {
            pack=packageManager.getPackageInfo("com.xunmeng.pinduoduo",0)
        }catch (e:PackageManager.NameNotFoundException){
            return false
        }
        return pack!=null
    }
    private fun goShare() {
        if (goodBean!!.pict_url !is String) {
            showToastMsg("该商品暂时不支持分享")
            return
        }
        val intent = Intent(this, GoodShareActivity::class.java)
        intent.putExtra("good", goodBean)
        startActivity(intent)
    }

    private fun goTaoBao() {
        showCountDownProgressDialog("请稍候", 3)
        alibcShowParams = AlibcShowParams(OpenType.Native, false)
        exParams = HashMap()
        exParams!![AlibcConstants.ISV_CODE] = "appisvcode"
        exParams!!["alibaba"] = "阿里巴巴"//自定义参数部分，可任意增删改

        // 若非淘客taokeParams设置为null即可
        val pid = Contacts.ALIMAMA_PID + AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams = AlibcTaokeParams()
        alibcTaokeParams?.adzoneid = AppUtils.getString(Contacts.ADZONE_ID, "")
        alibcTaokeParams?.pid = pid
        alibcTaokeParams?.subPid = pid
        alibcTaokeParams?.extraParams = HashMap()
        (alibcTaokeParams?.extraParams as HashMap<String, String>)["taokeAppkey"] = Contacts.APP_ID
        val url = if (goodBean!!.coupon_share_url != "https:" && goodBean!!.coupon_share_url != "") goodBean!!.coupon_share_url else goodBean!!.url
        AlibcTrade.show(this, AlibcPage(url), alibcShowParams, alibcTaokeParams, exParams, object : AlibcTradeCallback {
            override fun onTradeSuccess(tradeResult: AlibcTradeResult) {
                //当addCartPage加购成功和其他page支付成功的时候会回调
                if (tradeResult.resultType == AlibcResultType.TYPECART) {
                    //加购成功
                    showToastMsg("加购成功")
                } else if (tradeResult.resultType == AlibcResultType.TYPEPAY) {
                    //支付成功
//                    Log.d("order", tradeResult.payResult.paySuccessOrders[0])
                }
            }

            override fun onFailure(errCode: Int, errMsg: String) {
                showToastMsg("电商SDK出错,错误码=$errCode / 错误消息=$errMsg")
            }
        })
    }

    override fun onBackPressed() {
        if (mWebView.canGoBack()) {
            /*val fok=mWebView.copyBackForwardList()
            Log.e("eee","------>${fok.size}")
            if (fok!=null&&fok.size>0){
                val i=fok.currentIndex
                Log.e("eee目前","------>${i}")
                if (i==1){
                    finish()
                }
            }*/
            mWebView.goBack()
            /*title = ""
            itemId = ""
            goodBean = null
            tvToolBarTitle.text = intent!!.getStringExtra("name")
            clBotContainer.visibility = View.GONE
            tvTopTipContainer.visibility = View.GONE*/
        } else {
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
}
